package com.autoplaza;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.github.fabischmid.horizontalpager.withpagecontrol.HorizontalPagerWithPageControl;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Galeria extends Activity {
	private Gallery gallery;
    private ImageView imgView;
    private TextView marcamodelo, year;
	InputStream is = null;
	boolean metodo;
	String result,idanuncio;
	String[] array;
	Drawable image;
	String urlfotocodif;
	LinearLayout hs;
	private String marca2;
	private String modelo2;
	private String year2;
	private HorizontalPagerWithPageControl mPager;
	private ProgressDialog progressDialog;
	Bundle extras;
	
   
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.scrollgallery);
		
		int size = Utils.getScreenSize2(Galeria.this);
		if( size == 1){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(30, 30));
		}		
		if( size == 2){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 60));	
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(45, 45));

		}		
		if( size == 3){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 80));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(80, 80));

		}
		
		extras=this.getIntent().getExtras();
		
		if(isNetwork()){
			new LoadGalery().execute("");
		}else{
			
			dialogoInternet();
		}
		

    }
	
	
	
    private void crearImagenes() {
		hs = (LinearLayout) findViewById(R.id.hori);
		int[] dimen2 = Utils.getScreenSize(Galeria.this);
		int[] dimen = new int[2];
		if(!(dimen2[0]>dimen2[1])){
			dimen[0] = dimen2[0];
			dimen[1] = dimen2[1];
		}else{
			dimen[0] = dimen2[1];
			dimen[1] = dimen2[0];
		}
		Log.i("dimen[0]", ""+dimen[0]);
		Log.i("dimen[1]", ""+dimen[1]);

		
    	for(int i=0; i< array.length; i++){
    		
    		if(dimen[0] <= 320){
            	Log.i("DENSITY", "MEDIUM");
        		ImageView iv = new ImageView(this);
        		iv.setLayoutParams(new LayoutParams(150,113));
        		iv.setPadding(5, 0, 5, 0);
        		String url=array[i].replace(" ", "%20");
//        		iv.setOnClickListener(getOnClickDoSomething(""+url, i));

    			Drawable imagen = ImageOperations(getApplicationContext(),"","image.jpg", ""+url);
    			iv.setImageDrawable(imagen);

//            	iv.setImageResource(R.drawable.ic_launcher);
            	hs.addView(iv);
//            	mPager.addView(iv);
        	}else if( (dimen[0] > 320) && (dimen[0] <=480 )){
            	Log.i("DENSITY", "HIGH");
        		ImageView iv = new ImageView(this);
        		iv.setLayoutParams(new LayoutParams(300,225));
        		iv.setPadding(5, 0, 5, 0);
        		String url=array[i].replace(" ", "%20");
//        		iv.setOnClickListener(getOnClickDoSomething(""+url, i));

    			Drawable imagen = ImageOperations(getApplicationContext(),"","image.jpg", ""+url);
    			iv.setImageDrawable(imagen);

//            	iv.setImageResource(R.drawable.ic_launcher);
            	hs.addView(iv);
//            	mPager.addView(iv);
        	}else if(dimen[0] > 480){
            	Log.i("DENSITY", "EXTRA HIGH");
        		ImageView iv = new ImageView(this);
        		iv.setLayoutParams(new LayoutParams(360,270));
        		iv.setPadding(5, 0, 5, 0);
        		String url=array[i].replace(" ", "%20");
//        		iv.setOnClickListener(getOnClickDoSomething(""+url, i));

    			Drawable imagen = ImageOperations(getApplicationContext(),"","image.jpg", ""+url);
    			iv.setImageDrawable(imagen);

//            	iv.setImageResource(R.drawable.ic_launcher);
            	hs.addView(iv);
//            	mPager.addView(iv);
        	}
    	}
    }


	public class AddImgAdp extends BaseAdapter {
        int GalItemBg;
        private Context cont;

        public AddImgAdp(Context c) {
            cont = c;
            TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
            GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
            typArray.recycle();
        }

        public int getCount() {
            return array.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
			String url=array[position].replace(" ", "%20");

			Drawable imagen = ImageOperations(getApplicationContext(),"","image.jpg", url);

            ImageView imgView = new ImageView(cont);
			imgView.setImageDrawable(imagen);

//            imgView.setImageResource(Imgid[position]);
            imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
            imgView.setScaleType(ImageView.ScaleType.FIT_XY);
            imgView.setBackgroundResource(GalItemBg);
            return imgView;
        }
    }
	
	private void metodoinformacion(String numanuncio2) {

			
	     String url="http://iphone.autoplaza.com.mx/fotos/BuscFotos.aspx?id="+numanuncio2;
	        Log.i("url mia", ""+url);
			
			URI myURI = null;
			try {
				myURI = new URI(url);
			} catch (URISyntaxException e) {
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet getMethod = new HttpGet(myURI);
			HttpResponse webServerResponse = null;
			try {
				webServerResponse = httpClient.execute(getMethod);
			}  catch (IOException e) {
			}
			
			HttpEntity httpEntity = webServerResponse.getEntity();
	       
			
			if (httpEntity != null) {
		
				try {
					is = httpEntity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
		            StringBuilder sb = new StringBuilder();
		            String line = null;
		            while ((line = reader.readLine()) != null) {
		                    sb.append(line + "\n");
		            }
		            is.close();
		            result=sb.toString().trim();

		            array=result.split("@@@");
			           Log.i("TAM ARRAY", ""+array.length);


		            for(int i=0; i<array.length; i++){
		            	Log.i("MI ARRAY1["+i+"]", ""+array[i]);
		            }



				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
				}
			}
			
			
		
			
	}
	
	
	
	private Drawable ImageOperations(Context ctx, String url, String saveFilename, String myurl) {
		try {
			InputStream is = (InputStream) this.fetch(myurl);
			Drawable d = Drawable.createFromStream(is, "src");
			return d;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
		return null;
		}
	}

	public Object fetch(String address) throws MalformedURLException,IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}
		
    public boolean isNetwork(){
    	NetworkInfo networkInfo = ((ConnectivityManager) getApplicationContext()
	              .getSystemService(Context.CONNECTIVITY_SERVICE))
	              .getActiveNetworkInfo();

	            if(networkInfo == null || !networkInfo.isConnected()) {
	             return false;
	            }
	            return true;
    }
	
	
	
	View.OnClickListener getOnClickDoSomething(final String url, final int i)  {
	    return new View.OnClickListener() {
	        public void onClick(View v) {
	        	
//	        	ImageView im = (ImageView) findViewById(R.id.imagescroll);
//	        	Drawable imagen = ImageOperations(getApplicationContext(),"","image.jpg", ""+url);
//				im.setImageDrawable(imagen);
				
				mPager.setCurrentScreen(i, true);

	        }
	    };
	}
	
	
	public class LoadGalery extends AsyncTask<String, String, String>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(Galeria.this, "",
					"Cargando...", true, true, new OnCancelListener() {
						
						@Override
						public void onCancel(DialogInterface arg0) {
							finish();
						}
					});
		}
		
		
		@Override
		protected String doInBackground(String... params) {
			if(extras != null){
		        mPager = (HorizontalPagerWithPageControl) findViewById(R.id.horizontal_car_pager);
				idanuncio=extras.getString("idanuncio");
				marca2=extras.getString("marca");
				modelo2=extras.getString("modelo");
				year2=extras.getString("year");
				
				marcamodelo = (TextView) findViewById(R.id.marcamodelogallery);
				year = (TextView) findViewById(R.id.yeargallery);

				
				
				
				
				metodoinformacion(idanuncio);
				
				hs = (LinearLayout) findViewById(R.id.hori);
				
//	        	ImageView im = (ImageView) findViewById(R.id.imagescroll);
//	        	Drawable imagen = ImageOperations(getApplicationContext(),"","image.jpg", ""+array[0].replace(" ", "%20"));
//				im.setImageDrawable(imagen);
			}
			
			
			
			
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			marcamodelo.setText(""+marca2+" "+modelo2);
			year.setText("Año "+year2);
			crearImagenes();

			progressDialog.dismiss();
		}
		
	}
	
	
	private void dialogoInternet() {
		AlertDialog.Builder builder = new AlertDialog.Builder(Galeria.this);
		builder.setMessage("Necesita conexión a Internet")
		       .setCancelable(false)
		       .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		           }
		       });
		AlertDialog alertDialog = builder.create();
		alertDialog.show();		
								
	}
}
